package com.example.myapplication.utils;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import com.example.myapplication.App;
import com.example.myapplication.events.EventTTSFinish;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

public class TTSHelper {

    private static TTSHelper mInstance;

    private TextToSpeech mTTS;
    private boolean isReady;
    private TTSHelper() {
        mTTS = new TextToSpeech(App.AppContext
                , new TextToSpeech.OnInitListener() {
                    @Override
                    public void onInit(int status) {
                        isReady = status == TextToSpeech.SUCCESS;
                        if(isReady) {
                            mTTS.setLanguage(Locale.ENGLISH);
                        }
                    }
                });
        mTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String s) {}

            @Override
            public void onDone(String s) {
                EventBus.getDefault().post(new EventTTSFinish(s));
            }

            @Override
            public void onError(String s) {}
        });
    }

    public static TTSHelper getInstance() {
        if(mInstance == null)
            mInstance = new TTSHelper();
        return mInstance;
    }

    public void speak(String txt) {
        if(isReady) {
            mTTS.speak(txt, TextToSpeech.QUEUE_FLUSH, new Bundle(), "");
        }
    }


    public void synthesize(String txt) {
        if(isReady) {
            File file = App.AppContext.getExternalFilesDir("/voice.wav");
            file.delete();
            try {
                if(file.createNewFile()) {
                    mTTS.synthesizeToFile(txt, new Bundle(), file, file.getAbsolutePath());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
